<!--
 @description 创建验收任务
 @fileName Create.vue
 @author zengqiongying
 @created 2023/06/13 10:28:39
-->
<template>
  <div class="has-foot-pb" style="padding-top: 8px">
    <Card no-mg :round="false" style="margin-top: 0">
      <Cell title="验收门店" :modelValue="formData.sadAddress" placeholder="请选择" required @right="onSearchAddress" />
      <Cell
        v-if="formData.reportMold === '软装'"
        title="形象督导"
        :modelValue="formData.supervisionImage"
        placeholder="请选择"
        @right="onSearchSupervision"
      />
      <Cell
        v-if="formData.reportMold === '硬装'"
        title="工程监理"
        :modelValue="formData.projectSupervision"
        placeholder="请选择"
        @right="onSearchSupervision"
      />

      <Cell
        title="验收面积(㎡)"
        v-model="formData.acceptArea"
        type="number"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        inputAlign="right"
        required
      />
      <Cell title="门店编码" :modelValue="formData.storeCode" valueClassName="color-grey-normal" readonly />
      <Cell title="总面积" :modelValue="`${formData.totalArea || ''} ㎡`" valueClassName="color-grey-normal" readonly />

      <Cell title="验收人员" :modelValue="formData.ysSpecialist" placeholder="请选择" @right="onSearchYsUser" />
      <!-- <template v-if="pageSource !== 'task'">
        <Cell title="验收类型" :modelValue="formData.reportMold" valueClassName="color-grey-normal" readonly />
      </template>
      <template v-else> -->
      <!-- <FieldPicker
        v-model="formData.acceptMold"
        title="验收类型"
        placeholder="请选择"
        label-name="attributeValue"
        value-name="attributeValue"
        :optionData="[
          { attributeValue: '硬装验收' },
          { attributeValue: '软装验收' },
          { attributeValue: '硬装复查' },
          { attributeValue: '软装复查' }
        ]"
        clear
        required
      /> -->
      <FieldPicker
        v-model="formData.acceptMold"
        title="验收类型"
        placeholder="请选择"
        label-name="attributeValue"
        value-name="attributeValue"
        url="/app/TaskManage/GetDataDictionary"
        :params="{ query: { code: 'LX' }, type: 0 }"
        method="get"
        clear
        :includes="includeAcceptMolds"
        required
      />
      <!-- </template> -->
      <Cell
        title="装修项目号"
        v-model="formData.renovationProjectNo"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        inputAlign="right"
        required
      />
      <template v-if="pageSource !== 'task'">
        <Cell title="参与人员合照" is-column custom required readonly divider>
          <PartnerPhoto v-model="imagesList" :modelId="formData.caid" />
        </Cell>
        <Cell title="补充说明" is-column custom readonly>
          <qmp-field
            v-model="formData.supplementExplain"
            type="textarea"
            placeholder="输入内容"
            class="ctm-text-area"
          />
        </Cell>
      </template>
    </Card>
    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onCreate">
        {{ pageSource === 'task' ? '创建' : '开始验收' }}
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, watch } from 'vue'
  import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import FieldPicker from '@/components/FieldPicker/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import PartnerPhoto from '@/views/components/PartnerPhoto/index.vue'
  import { queryId } from '@/apis/common'
  import { createSaveTask } from '@/apis/Task'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  import { IAnyKeyObject } from '@/types/common'

  const none: any[] = [null, undefined, '']
  export default {
    name: 'TaskCreate',
    components: { Card, Cell, FieldPicker, PartnerPhoto },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $route = useRoute()
      const $router = useRouter()
      const datas = reactive<IAnyKeyObject>({
        pageSource: $route.query.source,
        formData: {
          caid: '',
          sadAddress: '',
          supervisionImage: '',
          projectSupervision: '',
          acceptArea: '',
          storeCode: '',
          storeAddress: '',
          totalArea: '',
          ysSpecialist: '',
          acceptMold: '',
          reportMold: '',
          renovationProjectNo: '',
          agency: '', // 办事处
          agentCode: '', // 经销商编码
          agentName: '',
          supplementExplain: ''
        },
        imagesList: [],
        includeAcceptMolds: [], // 排除验收类型
        keyboard: {
          show: false
        }
      })
      datas.keyboard = GetKeyboardMixin()

      if (datas.pageSource !== 'task') {
        datas.formData.ysSpecialist = $store.getters.userInfo.userName
        const reportMold = datas.pageSource === 'hard' ? '硬装' : '软装'
        datas.includeAcceptMolds = [`${reportMold}验收`, `${reportMold}复查`]
        datas.formData.acceptMold = `${reportMold}验收`
      }

      watch(
        () => datas.formData.acceptMold,
        (val, oldVal) => {
          if (val.indexOf('软装') > -1) {
            datas.formData.reportMold = '软装'
          } else if (val.indexOf('硬装') > -1) {
            datas.formData.reportMold = '硬装'
          } else {
            datas.formData.reportMold = ''
          }
        },
        {
          immediate: true
        }
      )

      // 选择验收门店
      const onSearchAddress = () => {
        const emitFuncName = 'TaskAddSetSadAddress'
        proxy.$SimpleEvents.registerEvent(emitFuncName, (data: any) => {
          onChangeAddress(data)
        })
        $router.push({
          path: '/search/sadAddress',
          query: {
            name: emitFuncName
          }
        })
      }
      // 选择形象督导
      const onSearchSupervision = () => {
        const emitFuncName = 'TaskAddSetSupervision'
        proxy.$SimpleEvents.registerEvent(emitFuncName, (data: any) => {
          onChangeSupervision(data)
        })
        $router.push({
          path: '/search/hrUser',
          query: {
            name: emitFuncName
          }
        })
      }

      // 选择验收人员
      const onSearchYsUser = () => {
        const emitFuncName = 'TaskAddSetYsUser'
        proxy.$SimpleEvents.registerEvent(emitFuncName, (data: any) => {
          onChangeYsUser(data)
        })
        $router.push({
          path: '/search/sasUser',
          query: {
            name: emitFuncName
          }
        })
      }

      const onChangeAddress = (d: any) => {
        // {code,name,customerName,customerCode,agencyName,agencyCode,operateArea,shopAddr}
        const storeData = {
          sadAddress: d?.name || '',
          storeCode: d?.code || '',
          totalArea: d?.operateArea || '',
          storeAddress: d?.shopAddr || '',
          agency: d?.agencyName || '',
          agentCode: d?.customerCode || '',
          agentName: d?.customerName || ''
        }
        datas.formData = { ...datas.formData, ...storeData }
      }

      const onChangeYsUser = (d: any) => {
        const names = d.map((v: any) => v.userName)
        datas.formData.ysSpecialist = names.join(',')
      }

      const onChangeSupervision = (d: any) => {
        const names = d.map((v: any) => v.staffName)
        if (datas.formData.reportMold === '软装') {
          datas.formData.supervisionImage = names.join(',')
          datas.formData.projectSupervision = ''
        } else {
          datas.formData.projectSupervision = names.join(',')
          datas.formData.supervisionImage = ''
        }
      }

      const onCreate = () => {
        const d = { ...datas.formData }
        if (!d.sadAddress) {
          proxy.$toast('请选择验收门店')
          return
        }
        if (none.includes(d.acceptArea)) {
          proxy.$toast('请输入验收面积')
          return
        } else {
          if (isNaN(d.acceptArea)) {
            proxy.$toast('验收面积只能是数字')
            return
          }
          if (Number(d.acceptArea || 0) === 0) {
            proxy.$toast('验收面积必须大于0')
            return
          }
        }
        /* if (none.includes(d.ysSpecialist)) {
          proxy.$toast('请选择验收人员')
          return
        } */
        if (none.includes(d.acceptMold)) {
          proxy.$toast('请选择验收类型')
          return
        }
        if (none.includes(d.renovationProjectNo)) {
          proxy.$toast('请输入装修项目号')
          return
        }

        if (datas.pageSource !== 'task' && datas.imagesList.length === 0) {
          proxy.$toast('请上传参与人员合照')
          return
        }
        if (d.reportMold === '硬装') {
          d.supervisionImage = ''
        } else {
          d.projectSupervision = ''
        }
        d.images = datas.imagesList.map((v: any) => {
          return v
        })
        saveFormData(d, (id: string) => {
          $router.goBack()
        })

        /* proxy.$dialog.confirm({
          title: '创建新增',
          message: '保存当前验收任务',
          lockScroll: true,
          confirmButtonText: '保存并验收',
          cancelButtonText: '保存并返回',
          closeOnClickOverlay: false,
          beforeClose: (action: any) => {
            return new Promise((resolve) => {
              if (!action) {
                resolve(true)
                return
              }
              setTimeout(() => {
                if (action === 'confirm') {
                  saveFormData(
                    d,
                    (id: string) => {
                      // 保存进入编辑
                      $router.replace({
                        path: '/task/detail',
                        query: {
                          source: datas.pageSource,
                          id
                        }
                      })
                      resolve(true)
                    },
                    () => {
                      resolve(true)
                    }
                  )
                } else if (action === 'cancel') {
                  // 保存并返回
                  saveFormData(
                    d,
                    (id: string) => {
                      // 保存进入编辑
                      $router.goBack()
                      resolve(true)
                    },
                    () => {
                      resolve(true)
                    }
                  )
                }
              }, 1000)
            })
          }
        }) */
      }

      // 保存新增数据
      const saveFormData = (data: any, callback?: any, closeback?: any) => {
        createSaveTask(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast('验收任务创建成功')
              // proxy.$SimpleEvents.emit('refreshTaskList')
              const tabName = none.includes(data.ysSpecialist) ? '1' : '2' // 1 未派发，2 验收中
              proxy.$SimpleEvents.emit('changeTaskListTab', tabName)
            } else {
              proxy.$toast('验收任务创建失败')
            }
            callback && callback(res?.msg)
            closeback && closeback()
          })
          .catch(() => {
            closeback && closeback()
          })
      }

      onBeforeRouteLeave((to, from, next) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['TaskManagement', 'HardCheckAccept', 'SoftCheckAccept'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
        next()
      })
      const getGuid = () => {
        queryId().then((res) => {
          datas.formData.caid = res.data || ''
        })
      }
      getGuid()

      return {
        ...toRefs(datas),
        onSearchAddress,
        onSearchSupervision,
        onSearchYsUser,
        onCreate
      }
    }
  }
</script>
<style lang="less" scoped></style>
